package own.stu.jobgib.playown.thrift.server;

import org.apache.thrift.TProcessorFactory;
import org.apache.thrift.protocol.TCompactProtocol;
import org.apache.thrift.protocol.TJSONProtocol;
import org.apache.thrift.server.*;
import org.apache.thrift.transport.TNonblockingServerSocket;
import org.apache.thrift.transport.TServerSocket;
import org.apache.thrift.transport.TTransportException;
import org.apache.thrift.transport.layered.TFramedTransport;
import own.stu.jobgib.playown.thrift.PersonService;
import own.stu.jobgib.playown.thrift.PersonServiceImpl;

public class ThriftServer {
    public static void main(String[] args) throws TTransportException {
//        startServer();
        TServer server = startServer_4();

        System.out.println("thrift server started .... ");
        server.serve();
    }

    private static TServer startServer_4() throws TTransportException {

        // 单线程非阻塞模型
        return new TNonblockingServer(
                new TNonblockingServer.Args(new TNonblockingServerSocket(8899))
                        .processor(builtProcessor()).transportFactory(new TFramedTransport.Factory())

        );
    }

    private static TServer startServer_3() throws TTransportException {
        // 多线程阻塞模型
        return new TThreadPoolServer(new TThreadPoolServer.Args(new TServerSocket(8899)).minWorkerThreads(2).maxWorkerThreads(2).processor(builtProcessor()));
    }

    private static TServer startServer_2() throws TTransportException {
        // TSimpleServer server = new TSimpleServer(new TServer.Args(new TServerSocket(8899)).processor(builtProcessor()));

        // 单线程阻塞模型
        return new TSimpleServer(new TServer.Args(new TServerSocket(8899))
                .protocolFactory(new TJSONProtocol.Factory()).processor(builtProcessor())
        );
    }

    private static TServer startServer() throws TTransportException {

        THsHaServer.Args arg = new THsHaServer.Args(new TNonblockingServerSocket(8899)).minWorkerThreads(2).maxWorkerThreads(4);

        PersonService.Processor<PersonServiceImpl> processor = builtProcessor();

        arg.protocolFactory(new TCompactProtocol.Factory())
                .transportFactory(new TFramedTransport.Factory())
                .processorFactory(new TProcessorFactory(processor));

        return new THsHaServer(arg);
    }

    private static PersonService.Processor builtProcessor() {
        return new PersonService.Processor<>(new PersonServiceImpl());
    }
}
